var fs = require('fs');
var path = require('path');
var request = require('request');
var urls = ['http://www.hao123.com/', 'http://www.baidu.com/'];

function makeRequest(url) {
	return new Promise(function(fullfil, reject) {
		request(url, function(err, res, body) {
			if (err) reject(err);
			fullfil(body);
		});
	})

	.then(function(text) {
		return text;
	})
}


function* main() {

	var foo = yield Promise.all(urls);
	var foo2 = foo.map(function(item) {
		return item.substring(0, 1);
	});
	var s = 'https://www.baidu.com/s?wd=' + foo2.join('');
	console.log(s);

	var r = yield makeRequest(s);
	console.log(r.substring(0, 10));
}

function runGen(gen) {
	var it = gen();
	var result;
	var count = 0;

	(function goNext(val) {
		console.log('goNext count=' + (++count));
		result = it.next(val);

		if (result.done) return;
		var v = result.value;
		if (typeof v === 'function') { // function
			console.log('function');
			v(goNext);
		} else if ('then' in v) { // promise
			console.log('then');
			// v.then(function(res) {
			// 	goNext(res);
			// });
			v.then(goNext);
		} else { // direct value 
			// avoid synchronous recursion ==>学了一招
			console.log('direct value');
			process.nextTick(function() {
				goNext(it.next(v));
			});
		}
	})();
}

runGen(main);